<?php
namespace app\common\model\orderdata;

use think\Model;
use app\common\model\company\Contract;
use app\common\model\company\ContractDetails;

class Goods extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'goods';
    protected $pk    = 'GoodId';

    const STATEOK  = 1; //1为选择生效的 目前为0 是因为全部 显示
    const STATEINT = 1;

    // public function getOrderNumberAttr($value,$data)
    // {
    //     if(!empty($data['AnotherName'])){
    //         return $value.'('.$data['AnotherName'].')';
    //     }
    //     return $value;
    // }

    public function getAnotherNameAttr($value)
    {
        if (!empty($value)) {
            if (strstr($value, ',') !== false) {
                return explode(',', $value);
            } else if (strstr($value, ';') !== false) {
                return explode(';', $value);
            } else {
                return [$value];
            }
        } else {
            return [];
        }
    }

    public function getHarmfulListAttr($value)
    {
        if (!empty($value)) {
            if (strstr($value, ',') !== false) {
                return explode(',', $value);
            } else if (strstr($value, ';') !== false) {
                return explode(';', $value);
            } else {
                return [$value];
            }
        } else {
            return [];
        }
    }

    /**
     * 获取产品列表
     * @return [type] [description]
     */
    public static function get_ordernumber_list($str)
    {
        if(empty($str)){
            return [];
        }
        $data = Goods::where('State', Goods::STATEOK);
        $data = $data->where('OrderNumber','in',$str);
        $data = $data->select();
        $data->hidden(['TotalWeight', 'OperationLog']);
        $data = $data->toArray();
        return $data;  
    }
    /**
     * 获取产品列表
     * @return [type] [description]
     */
    public static function getlist($id = [],$companyid='')
    {
        $data = Goods::where('State', Goods::STATEOK)->order('Type asc');
        if (!empty($id)) {
            $data = $data->where('GoodId', 'in', $id);
        }
        $data = $data->select();
        $data->hidden(['TotalWeight', 'OperationLog']);
        $data = $data->toArray();
        if(!empty($companyid)){
            $contractId = Contract::where('CompanyId',$companyid)->column('ContractId');
            $goodidarr = ContractDetails::where('ContractId','in',$contractId)->column('GoodId');
            $goodidarr = array_unique($goodidarr);
            if(!empty($goodidarr)){
                $ndata = Goods::where('State', Goods::STATEOK)->where('GoodId', 'in', $goodidarr)->order('Type asc')->select();
                $ndata->hidden(['TotalWeight', 'OperationLog']);
                $ndata = $ndata->toArray();
                foreach ($ndata as $key => $value) {
                    $ndata[$key]['OrderNumber'] = $ndata[$key]['OrderNumber'].'('.$value['Type'].')';
                    $ndata[$key]['Type'] = '合同关联';
                }
                $data = array_merge($ndata,$data);
            }
        }
        return $data;
    }
    /**
     * 判断列表中的产品状态是否可操作
     * @param  [type] $list [id数组]
     * @return [type]       [返回错误代码]
     */
    public static function list_state($list)
    {
        $data = Goods::where('State', '<>', Goods::STATEOK)->where('GoodId', 'in', $list)->order('Type asc')->column('OrderNumber');
        if (!empty($data)) {
            $str = implode("\n", $data);
            $str = "以下危废无法使用：\n" . $str;
            return serr($str);
        } else {
            return sok();
        }
    }

    /**
     * 修改货物重量
     * @param  [type] $GoodIds [description]
     * @param  [type] $weights [description]
     * @param  string $type    [add sub]
     * @return [type]          [description]
     */
    public static function weight_change($GoodIds, $weights, $type = 'add')
    {
        if (!is_array($GoodIds)) {
            if (stripos($GoodIds, ',') !== false) {
                $GoodIds = explode($GoodIds, ',');
                $weights = explode($weights, ',');
            } else {
                $GoodIds = [$GoodIds];
                $weights = [$weights];
            }
        }
        //按照货物id从新调整数顺序
        $nweights = [];
        if ($type == 'add') {
            foreach ($GoodIds as $key => $value) {
                $nweights[$value] = (empty($nweights[$value])?0:$nweights[$value])+$weights[$key];
            }
        } else if ($type == 'sub') {
            foreach ($GoodIds as $key => $value) {
                $nweights[$value] = (empty($nweights[$value])?0:$nweights[$value]) + -1 * $weights[$key];
            }
        }
        //检测货物是否足够减少
        $sb = Goods::where('GoodId', 'in', $GoodIds)->select();
        if ($type == 'sub') {
            foreach ($sb as $key => $data) {
                if (((empty($data->TotalWeight) ? 0 : $data->TotalWeight) + $nweights[$data->GoodId]) < 0) {
                    return serr($data->OrderNumber . '的库存重量不足以调整');
                }
            }
        }
        //调整库存
        foreach ($sb as $key => $data) {
            if (empty($data->TotalWeight)) {
                $data->TotalWeight = $nweights[$data->GoodId];
            } else {
                $data->TotalWeight = $data->TotalWeight + $nweights[$data->GoodId];
            }
            $data->save();
        }
        return sok();
    }

    /**
     * 获取库存重量
     * @return [type] [description]
     */
    public static function getwarelist()
    {
        $data = Goods::where('State', Goods::STATEOK);
        $data = $data->where('TotalWeight', '>', 0);
        $data = $data->select();
        $data->hidden(['OperationLog']);
        return $data;
    }

    /**
     * 获取库存重量
     * @return [type] [description]
     */
    public static function getweightlist($ids)
    {
        $data = Goods::where('State', Goods::STATEOK);
        $data = $data->where('GoodId', 'in', $ids)->order('Type asc');
        $data = $data->column('GoodId,TotalWeight');
        return $data;
    }

    /**
     * 完善危废名称
     * @param [type] $idlist   [description]
     * @param [type] $namelist [description]
     */
    public static function NamePerfect($idlist, $namelist)
    {
        $goodlist = Goods::where('GoodId', 'in', $idlist)->column('AnotherName', 'GoodId');

        $changesb = [];
        foreach ($idlist as $key => $value) {
            if (empty($goodlist[$value])) {
                $goodlist[$value] = $namelist[$key];
                $changesb[$value] = 1;
            } else if (!empty($namelist[$key])&&strpos($goodlist[$value], $namelist[$key]) === false) {
                $goodlist[$value] = $goodlist[$value] . ',' . $namelist[$key];
                $changesb[$value] = 1;
            }
        }
        $updatelist = [];
        foreach ($changesb as $key => $value) {
            $updatelist[] = ['GoodId' => $key, 'AnotherName' => $goodlist[$key]];
        }
        $goods = new Goods;
        $goods->saveAll($updatelist);
    }

    /**
     * 完善危废有害成分
     * @param [type] $idlist   [description]
     * @param [type] $namelist [description]
     */
    public static function HarmfulListPerfect($idlist, $harmfullist)
    {
        $goodlist = Goods::where('GoodId', 'in', $idlist)->column('HarmfulList', 'GoodId');

        $changesb = [];
        foreach ($idlist as $key => $value) {
            if (empty($goodlist[$value])) {
                $goodlist[$value] = $harmfullist[$key];
                $changesb[$value] = 1;
            } else {
                if(!empty($harmfullist[$key])){
                    if(strpos($harmfullist[$key],',')){
                        $lslist = explode($harmfullist[$key],',');
                    }else if(strpos($harmfullist[$key],';')){
                        $lslist = explode($harmfullist[$key],';');
                    }else{
                        $lslist = [$harmfullist[$key]];
                    }
                    foreach ($lslist as $key2 => $value2) {
                        if (strpos($goodlist[$value], $harmfullist[$key]) === false) {
                            $goodlist[$value] = $goodlist[$value] . ',' . $harmfullist[$key];
                            $changesb[$value] = 1;
                        }
                    }
                }
            }
        }
        $updatelist = [];
        foreach ($changesb as $key => $value) {
            $updatelist[] = ['GoodId' => $key, 'HarmfulList' => $goodlist[$key]];
        }
        $goods = new Goods;
        $goods->saveAll($updatelist);
    }

	public function storageAreaGoods()
	{
		return $this->hasMany(StorageAreaGoods::class, 'GoodId', 'GoodId');
    }
}
